package com.southminority.ethnic.service.research.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.southminority.ethnic.common.exception.BusinessException;
import com.southminority.ethnic.mapper.research.ResearchProgressMapper;
import com.southminority.ethnic.pojo.ResearchProgress;
import com.southminority.ethnic.service.research.ResearchProgressService;
import com.southminority.ethnic.vo.AttachmentFileVO;
import com.southminority.ethnic.controller.research.vo.ResearchProgressVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 研究进展服务实现类
 * 
 * @author SouthMinority
 */
@Slf4j
@Service
public class ResearchProgressServiceImpl implements ResearchProgressService {

    private final ResearchProgressMapper researchProgressMapper;
    private final ObjectMapper objectMapper;

    public ResearchProgressServiceImpl(ResearchProgressMapper researchProgressMapper, 
                                     ObjectMapper objectMapper) {
        this.researchProgressMapper = researchProgressMapper;
        this.objectMapper = objectMapper;
    }

    @Override
    public List<ResearchProgressVO> getResearchProgressList() {
        QueryWrapper<ResearchProgress> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1)
               .orderByDesc("progress_date")
               .orderByDesc("create_time");

        List<ResearchProgress> progressList = researchProgressMapper.selectList(wrapper);
        return progressList.stream()
                          .map(this::convertToVO)
                          .collect(Collectors.toList());
    }

    @Override
    public List<ResearchProgressVO> getResearchProgressList(Long organizationId) {
        QueryWrapper<ResearchProgress> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1);
        if (organizationId != null) {
            wrapper.eq("organization_id", organizationId);
        }
        wrapper.orderByDesc("progress_date").orderByDesc("create_time");
        List<ResearchProgress> list = researchProgressMapper.selectList(wrapper);
        return list.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    @Override
    public List<ResearchProgressVO> getTimelineResearchProgressList() {
        QueryWrapper<ResearchProgress> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1)
               .eq("is_timeline", 1)
               .orderByDesc("progress_date")
               .orderByDesc("create_time");

        List<ResearchProgress> progressList = researchProgressMapper.selectList(wrapper);
        return progressList.stream()
                          .map(this::convertToVO)
                          .collect(Collectors.toList());
    }

    @Override
    public List<ResearchProgressVO> getTimelineResearchProgressList(Long organizationId) {
        QueryWrapper<ResearchProgress> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1).eq("is_timeline", 1);
        if (organizationId != null) {
            wrapper.eq("organization_id", organizationId);
        }
        wrapper.orderByDesc("progress_date").orderByDesc("create_time");
        List<ResearchProgress> list = researchProgressMapper.selectList(wrapper);
        return list.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    @Override
    public List<ResearchProgressVO> getFeaturedResearchProgressList() {
        QueryWrapper<ResearchProgress> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1)
               .eq("is_featured", 1)
               .orderByAsc("sort_order")
               .orderByDesc("progress_date");

        List<ResearchProgress> progressList = researchProgressMapper.selectList(wrapper);
        return progressList.stream()
                          .map(this::convertToVO)
                          .collect(Collectors.toList());
    }

    @Override
    public List<ResearchProgressVO> getFeaturedResearchProgressList(Long organizationId) {
        QueryWrapper<ResearchProgress> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1).eq("is_featured", 1);
        if (organizationId != null) {
            wrapper.eq("organization_id", organizationId);
        }
        wrapper.orderByAsc("sort_order").orderByDesc("progress_date");
        List<ResearchProgress> list = researchProgressMapper.selectList(wrapper);
        return list.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    @Override
    public ResearchProgressVO getResearchProgressDetail(Long id) {
        if (id == null) {
            throw new BusinessException("研究进展ID不能为空");
        }

        ResearchProgress progress = researchProgressMapper.selectById(id);
        if (progress == null || progress.getStatus() == -1) {
            throw new BusinessException("研究进展不存在");
        }

        // 增加浏览次数
        progress.setViewCount((progress.getViewCount() == null ? 0 : progress.getViewCount()) + 1);
        researchProgressMapper.updateById(progress);

        return convertToVO(progress);
    }

    @Override
    public List<ResearchProgressVO> getResearchProgressByProject(Long projectId) {
        if (projectId == null) {
            throw new BusinessException("项目ID不能为空");
        }

        QueryWrapper<ResearchProgress> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1)
               .eq("project_id", projectId)
               .orderByDesc("progress_date")
               .orderByDesc("create_time");

        List<ResearchProgress> progressList = researchProgressMapper.selectList(wrapper);
        return progressList.stream()
                          .map(this::convertToVO)
                          .collect(Collectors.toList());
    }

    @Override
    public List<ResearchProgressVO> getResearchProgressByField(String researchField) {
        if (researchField == null || researchField.trim().isEmpty()) {
            throw new BusinessException("研究领域不能为空");
        }

        QueryWrapper<ResearchProgress> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1)
               .eq("research_field", researchField.trim())
               .orderByDesc("progress_date")
               .orderByDesc("create_time");

        List<ResearchProgress> progressList = researchProgressMapper.selectList(wrapper);
        return progressList.stream()
                          .map(this::convertToVO)
                          .collect(Collectors.toList());
    }

    @Override
    public List<ResearchProgressVO> getRecentResearchProgress(Integer limit) {
        if (limit == null || limit <= 0) {
            limit = 5; // 默认返回5条
        }

        QueryWrapper<ResearchProgress> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1)
               .orderByDesc("progress_date")
               .orderByDesc("create_time")
               .last("LIMIT " + limit);

        List<ResearchProgress> progressList = researchProgressMapper.selectList(wrapper);
        return progressList.stream()
                          .map(this::convertToVO)
                          .collect(Collectors.toList());
    }

    @Override
    public List<ResearchProgressVO> getRecentResearchProgress(Integer limit, Long organizationId) {
        if (limit == null || limit <= 0) {
            limit = 5;
        }
        QueryWrapper<ResearchProgress> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1);
        if (organizationId != null) {
            wrapper.eq("organization_id", organizationId);
        }
        wrapper.orderByDesc("progress_date").orderByDesc("create_time").last("LIMIT " + limit);
        List<ResearchProgress> list = researchProgressMapper.selectList(wrapper);
        return list.stream().map(this::convertToVO).collect(Collectors.toList());
    }

    private ResearchProgressVO convertToVO(ResearchProgress progress) {
        if (progress == null) {
            return null;
        }

        ResearchProgressVO vo = new ResearchProgressVO();
        BeanUtils.copyProperties(progress, vo);

        try {
            if (progress.getAchievements() != null && !progress.getAchievements().trim().isEmpty()) {
                List<String> achievements = objectMapper.readValue(
                    progress.getAchievements(),
                    new TypeReference<List<String>>() {}
                );
                vo.setAchievements(achievements);
            } else {
                vo.setAchievements(Collections.emptyList());
            }
        } catch (Exception e) {
            log.error("解析研究进展成就JSON失败，进展ID: {}, JSON: {}", progress.getId(), progress.getAchievements(), e);
            vo.setAchievements(Collections.emptyList());
        }

        try {
            if (progress.getMilestones() != null && !progress.getMilestones().trim().isEmpty()) {
                List<String> milestones = objectMapper.readValue(
                    progress.getMilestones(),
                    new TypeReference<List<String>>() {}
                );
                vo.setMilestones(milestones);
            } else {
                vo.setMilestones(Collections.emptyList());
            }
        } catch (Exception e) {
            log.error("解析研究进展里程碑JSON失败，进展ID: {}, JSON: {}", progress.getId(), progress.getMilestones(), e);
            vo.setMilestones(Collections.emptyList());
        }

        try {
            if (progress.getParticipants() != null && !progress.getParticipants().trim().isEmpty()) {
                List<String> participants = objectMapper.readValue(
                    progress.getParticipants(),
                    new TypeReference<List<String>>() {}
                );
                vo.setParticipants(participants);
            } else {
                vo.setParticipants(Collections.emptyList());
            }
        } catch (Exception e) {
            log.error("解析研究进展参与人员JSON失败，进展ID: {}, JSON: {}", progress.getId(), progress.getParticipants(), e);
            vo.setParticipants(Collections.emptyList());
        }

        try {
            if (progress.getImageUrls() != null && !progress.getImageUrls().trim().isEmpty()) {
                List<String> imageUrls = objectMapper.readValue(
                    progress.getImageUrls(),
                    new TypeReference<List<String>>() {}
                );
                vo.setImageUrls(imageUrls);
            } else {
                vo.setImageUrls(Collections.emptyList());
            }
        } catch (Exception e) {
            log.error("解析研究进展图片URLs JSON失败，进展ID: {}, JSON: {}", progress.getId(), progress.getImageUrls(), e);
            vo.setImageUrls(Collections.emptyList());
        }

        try {
            if (progress.getAttachmentUrls() != null && !progress.getAttachmentUrls().trim().isEmpty()) {
                List<AttachmentFileVO> attachmentUrls = objectMapper.readValue(
                    progress.getAttachmentUrls(),
                    objectMapper.getTypeFactory().constructCollectionType(List.class, AttachmentFileVO.class)
                );
                vo.setAttachmentUrls(attachmentUrls);
            } else {
                vo.setAttachmentUrls(Collections.emptyList());
            }
        } catch (Exception e) {
            log.error("解析研究进展附件URLs JSON失败，进展ID: {}, JSON: {}", progress.getId(), progress.getAttachmentUrls(), e);
            vo.setAttachmentUrls(Collections.emptyList());
        }

        return vo;
    }
} 
